﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using KnowledgeKiosk.Parsers;
using KnowledgeKiosk.SharePointService;

namespace KnowledgeKiosk.FeedUpdaters
{
    /// <summary>
    /// Provides a way to periodically load and deserialize items from a SharePoint List
    /// </summary>
    /// <typeparam name="T">Specifies the type of objects that will be retrieved.</typeparam>
    public class SharePointListItemsFeedUpdater<T> : AbstractXmlFeedUpdater<T>
    {
        /// <summary>
        /// Initializes a new instance of the SharePointListItemsFeedUpdater(Of T) class using the specified
        /// SharePoint Lists Web Service Uri, SharePoint List ID, Xml-to-Object parser and update interval.
        /// </summary>
        /// <param name="listServiceUri">Uri of the SharePoint Lists Web Service</param>
        /// <param name="listID">ID of the SharePoint List</param>
        /// <param name="xmlParser">Parser that translates XML to strongly typed objects.</param>
        /// <param name="updateInterval">Interval of the update cycle.</param>
        public SharePointListItemsFeedUpdater(Uri listServiceUri, Guid listID, IXmlToObjectParser<T> xmlParser,
                                              TimeSpan updateInterval)
            : base(listServiceUri, xmlParser, updateInterval)
        {
            ListID = listID;
        }

        /// <summary>
        /// Gets the ID of the SharePoint List
        /// </summary>
        public Guid ListID { get; private set; }

        /// <summary>
        /// Called when the update interval has elapsed.
        /// </summary>
        internal override void Tick(object sender, EventArgs e)
        {
            Binding binding = new BasicHttpBinding();
            var endpoint = new EndpointAddress(FeedUri);
            var spClient = new ListsSoapClient(binding, endpoint);
            spClient.GetListItemsCompleted += GetListItemsCompleted;
            spClient.GetListItemsAsync(ListID.ToString(), null, null, null, null, null, null);
        }

        /// <summary>
        /// Called when the SharePoint Lists Web Service has returned a response.
        /// </summary>
        /// <param name="sender">The control that raised the event.</param>
        /// <param name="e">The contents of the queried SharePoint List.</param>
        private void GetListItemsCompleted(object sender, GetListItemsCompletedEventArgs e)
        {
            try
            {
                ParseXmlData(e.Result);
                if (RetryEnabled && IsRetrying)
                    ResetRetryInterval();
            }
            catch(Exception ex)
            {
                Logger.WriteLine(ex);

                SetRetryInterval();
            }
        }
    }
}